package com.luca.web.controller.system;

import com.luca.common.constant.Constants;
import com.luca.common.core.domain.JsonResult;
import com.luca.common.core.domain.entity.SysMenu;
import com.luca.common.core.domain.entity.SysUser;
import com.luca.common.core.domain.model.LoginBody;
import com.luca.common.utils.SecurityUtils;
import com.luca.framework.web.service.SysLoginService;
import com.luca.framework.web.service.SysPermissionService;
import com.luca.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 *
 * @author luca
 */
@RestController
public class SysLoginController {

    private final SysLoginService loginService;

    private final ISysMenuService menuService;

    private final SysPermissionService permissionService;

    @Autowired
    public SysLoginController(SysLoginService loginService, ISysMenuService menuService, SysPermissionService permissionService) {
        this.loginService = loginService;
        this.menuService = menuService;
        this.permissionService = permissionService;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public JsonResult login(@RequestBody LoginBody loginBody) {
        // 生成令牌
        String token = loginService.login(loginBody.getCode(), loginBody.getUsername(), loginBody.getPassword(), loginBody.getCaptcha(),
                loginBody.getUuid(), loginBody.getUserType());
        return JsonResult.success(Map.of(Constants.TOKEN, token));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public JsonResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        JsonResult res = JsonResult.success();
        res.put("user" , user);
        res.put("roles" , roles);
        res.put("permissions" , permissions);
        return res;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public JsonResult getRouters() {
        // 用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user);
        return JsonResult.success(menuService.buildMenus(menus));
    }
}
